import constant from './constant'

// 存储变量名
let storageKey = 'storage_data'

// 存储节点变量名
let storageNodeKeys = [constant.avatar, constant.id, constant.name, constant.roles, constant.permissions]

const storage = {
	set: function(key, value) {
		if (storageNodeKeys.indexOf(key) != -1) {
			let tmp = uni.getStorageSync(storageKey)
			tmp = tmp ? tmp : {}
			tmp[key] = value
			uni.setStorageSync(storageKey, tmp)
		}
	},
	get: function(key) {
		let storageData = uni.getStorageSync(storageKey) || {}
		return storageData[key] || ""
	},
	remove: function(key) {
		let storageData = uni.getStorageSync(storageKey) || {}
		delete storageData[key]
		uni.setStorageSync(storageKey, storageData)
	},
	clean: function() {
		uni.removeStorageSync(storageKey)
	}
}

export default storage



// utils/storage.js

/**
 * 清空缓存，但保留指定的 key
 * @param {Array<string>} keysToKeep - 要保留的 key 列表
 */
export function clearStorageExcept(keysToKeep = []) {
	const saved = {}

	// 1️⃣ 保存需要保留的 key 的值
	keysToKeep.forEach(key => {
		const value = uni.getStorageSync(key)
		if (value !== undefined && value !== null) {
			saved[key] = value
		}
	})

	// 2️⃣ 清空所有缓存
	uni.clearStorage()

	// 3️⃣ 重新写回需要保留的 key
	Object.keys(saved).forEach(key => {
		uni.setStorageSync(key, saved[key])
	})
}